package org.mdrtwell.jdbc;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.PrintStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class BlobOperationCase {
	private Connection	conn;

	public Connection getConnection() {
		try {
			Class.forName("oracle.jdbc.driver.OracleDriver");
			conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:lyx",
					"scott",
					"tiger");
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return conn;
	}

	public int insertImage(String path) throws Exception {
		int i = 0;
		Statement st = null;
		ResultSet rs = null;
		conn = this.getConnection();
		conn.setAutoCommit(false);
		st = conn.createStatement();
		i = st.executeUpdate("insert into image (id,image) values (seq1.nextval,Empty_BLOB())");
		rs = st.executeQuery("select image from image where id=(select max(id) from image) for update");
		if (rs.next()) {
			oracle.sql.BLOB blob = (oracle.sql.BLOB) rs.getBlob(1);
			PrintStream ps = new PrintStream(blob.getBinaryOutputStream());
			BufferedInputStream bis = new BufferedInputStream(new FileInputStream(path));
			byte[] buff = new byte[1024];
			int n = 0;
			while ((n = bis.read(buff)) != -1) {
				ps.write(buff, 0, n);
			}
			ps.flush();
			ps.close();
			bis.close();
		}
		rs.close();
		st.close();
		conn.close();
		return i;
	}

	public static void main(String[] args) throws Exception {
		BlobOperationCase test = new BlobOperationCase();
		test.insertImage("e:\\3.jpg");
		System.out.println("OK");
	}
}
